package com.xzxy.xmlg_backend.controller;

import com.xzxy.xmlg_backend.entity.Result;
import com.xzxy.xmlg_backend.service.AnnouncementScheduleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 定时任务测试控制器
 * @author 周毅盛
 * @since 2025-06-16
 */
@RestController
@RequestMapping("/schedule-test")
@Tag(name = "定时任务测试")
public class ScheduleTestController {

    @Autowired
    private AnnouncementScheduleService scheduleService;

    /**
     * 获取当前定时任务状态
     */
    @GetMapping("/status")
    @Operation(summary = "获取定时任务状态", description = "获取当前所有定时任务的状态信息")
    public Result getScheduleStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("currentTime", LocalDateTime.now());
        status.put("scheduledTaskCount", scheduleService.getScheduledTaskCount());
        status.put("systemTimeZone", System.getProperty("user.timezone"));
        return Result.success(status);
    }

    /**
     * 检查指定公告是否有定时任务
     */
    @GetMapping("/check/{announcementId}")
    @Operation(summary = "检查公告定时任务", description = "检查指定公告是否存在定时任务")
    public Result checkAnnouncementTask(@PathVariable Integer announcementId) {
        boolean hasTask = scheduleService.hasScheduledTask(announcementId);
        Map<String, Object> result = new HashMap<>();
        result.put("announcementId", announcementId);
        result.put("hasScheduledTask", hasTask);
        result.put("currentTime", LocalDateTime.now());
        return Result.success(result);
    }

    /**
     * 手动触发定时任务测试
     */
    @PostMapping("/test/{announcementId}")
    @Operation(summary = "测试定时任务", description = "创建一个1分钟后执行的测试定时任务")
    public Result testScheduleTask(@PathVariable Integer announcementId) {
        try {
            // 创建一个1分钟后执行的测试任务
            LocalDateTime testTime = LocalDateTime.now().plusMinutes(1);
            scheduleService.scheduleAnnouncement(announcementId, testTime);
            
            Map<String, Object> result = new HashMap<>();
            result.put("message", "测试定时任务已创建");
            result.put("announcementId", announcementId);
            result.put("scheduledTime", testTime);
            result.put("currentTime", LocalDateTime.now());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("创建测试任务失败: " + e.getMessage());
        }
    }
}